﻿using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Brushes;
using Microsoft.Graphics.Canvas.Effects;
using Microsoft.Graphics.Canvas.UI.Xaml;
using System;
using System.Collections.Generic;

using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using Windows.UI;
using 纸片人.Shaders;

namespace 纸片人.win2dEffectControl.DataClass.PixelShaderEffectDataClass
{
    public class GradienMappingEffectData : PixelShaderEffectData
    {
        private Color[] mapColors;


        /// <summary>
        /// 临界点 0-1
        /// </summary>
        public Color[] MapColors { get => mapColors; set { mapColors = value; OnPropertyChanged(); SetIsChanges(); } }


        public override ShaderType shaderShaderPath { get; } = ShaderType.GradientMapping;

        public override ICanvasImage GetEffect(CanvasDevice device, bool compression)
        {
            var source = GetSourceEffect(device, compression);
            if (source == null || MapColors == null)
            {
                return null;
            }

            if (shaderCodeBytes == null)
                return null;
       

            CanvasRenderTarget crt = new CanvasRenderTarget(device, 256,1, 96);
          
            using (var ds = crt.CreateDrawingSession())
            {
                var canvasGradienStop = new CanvasGradientStop[MapColors.Length];
                for (int i = 0; i < MapColors.Length; i++)
                {
                    canvasGradienStop[i] = new CanvasGradientStop
                    {
                        Color = MapColors[i],
                        Position = (float)i / (float)(MapColors.Length - 1)
                    };
                }
                CanvasLinearGradientBrush linearBrush = new CanvasLinearGradientBrush(device, canvasGradienStop)
                {
                    StartPoint = new Vector2(0, 0),
                    EndPoint = new Vector2(256, 0),
                };
                ds.FillRectangle(0, 0, 256, 1, linearBrush);
            }

            PixelShaderEffect effect = new PixelShaderEffect(shaderCodeBytes)
            {
                Source1 = source,
                Source2 = crt,
                Source2BorderMode = EffectBorderMode.Hard
            };
            return effect;
        }
    }
}
